package dao;

import model.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.DBUtil;

import java.sql.SQLException;

public class UserDao {
    //添加用户
    public void addUser(User user) throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql = "insert into user(username,email,password,name,phone,address,isadmin,isvalidate) values(?,?,?,?,?,?,?,?)";
        r.update(sql,user.getUsername(),user.getEmail(),user.getPassword(),user.getName(),user.getPhone(),user.getAddress(),user.isIsadmin(),user.isIsvalidate());
    }
    //如果用户名和用户邮箱存在就不可以注册
    //用户名
    public boolean isUsernameExist(String username) throws SQLException {
            QueryRunner r = new QueryRunner(DBUtil.getDataSource());
            String sql = "select * from user where username=?";
            User u = r.query(sql,new BeanHandler<User>(User.class),username);
            if(u==null)
                return false;
            else
                return true;
    }
    //邮箱
    public boolean isEmailExist(String email) throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql = "select * from user where email=?";
        User u = r.query(sql,new BeanHandler<User>(User.class),email);
        if(u==null)
            return false;
        else
            return true;
    }
    //数据库查询用户
    //通过账号密码查询
    public User selectByUsernamePassword(String username,String password) throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql = "select * from user where username=? and password=?";
        return r.query(sql, new BeanHandler<User>(User.class),username,password);
    }
    //通过邮箱密码查询
    public User selectByEmailPassword(String email,String password) throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql = "select * from user where email=? and password=?";
        return r.query(sql, new BeanHandler<User>(User.class),email,password);
    }
    //更新个人中心的收货地址
    public void updateUserAddress(User user) throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql ="update user set name = ?,email=?,phone=?,address=? where id = ?";
        r.update(sql,user.getName(),user.getEmail(),user.getPhone(),user.getAddress(),user.getId());
    }
    //更新个人中心的密码
    public void updatePwd(User user) throws SQLException {
        QueryRunner r = new QueryRunner(DBUtil.getDataSource());
        String sql ="update user set password = ? where id = ?";
        r.update(sql,user.getPassword(),user.getId());
    }






}
